<?php
/**
 * Created by PhpStorm.
 * User: bob
 * Date: 2022/10/18
 * Time: 14:18
 */

declare(strict_types=1);

namespace App\Job;

use App\Cache\SocketRoom;
use App\Constant\TalkMessageType;
use App\Model\Group\Group;
use App\Service\SocketClientService;
use Hyperf\AsyncQueue\Job;
use Hyperf\Utils\ApplicationContext;
use App\Service\Message\FormatMessageService;
use App\Constant\TalkEventConstant;

class ExampleJob extends Job
{
    public $params;

    /**
     * 任务执行失败后的重试次数，即最大执行次数为 $maxAttempts+1 次
     *
     * @var int
     */
    protected $maxAttempts = 2;


    public function __construct($params)
    {
        $this->params = $params;
    }

    public function handle()
    {
        // 点位、赛事名、设备名、发钉钉，电话

        info('examjob', $this->params);
        $receiver_id = data_get($this->params, 'receiver_id', 0);
        $sender_id = data_get($this->params, 'sender_id', 0);
        $group = Group::find($receiver_id);

        $message = di()->get(FormatMessageService::class)->handleChatRecords([['activity_id' => data_get($group, 'activity_id'), 'msg_type' => TalkMessageType::RANK_MESSAGE, 'force' => 1]])[0];

        $clientService = new SocketClientService();
        $fds = [];
        foreach (SocketRoom::getInstance()->getRoomMembers(strval($receiver_id)) as $uid) {
            $fds[] = $clientService->findUserFds(intval($uid));
        }

//        info('mes', [$message, $fds]);
        $sender = new \Hyperf\WebSocketServer\Sender(ApplicationContext::getContainer());
        if (empty($fds)) return;

        $fds = array_unique(array_merge(...$fds));

        // 客户端ID去重
        if (!$fds) return;

        if ($fds) {
            try {
                foreach ($fds as $fd) {
                    $res = $sender->push((int)$fd, json_encode(['event' => TalkEventConstant::EVENT_TALK, 'content' => [
                        'sender_id'   => 0,
                        'receiver_id' => 0,
                        'talk_type'   => 2,
                        'data'        => $message
                    ]]));
                }
            } catch (\Exception $e) {}
        }
    }
}